package com.erp.hrms.utils;

import com.erp.hrms.enums.Atom;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES算法进行加密
 *
 * @author CodeGeek
 * @create 2018-01-23 上午11:00
 */
@Slf4j
public class EncryptUtil {

    /**
     * 加密
     *
     * @param content
     * @param password
     * @return
     */
    public static String encrypt(String content, String password) {
        try {
            SecretKeySpec key = createCipher(password);
            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES");
            // 设置转换格式
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, key);
            // 加密
            byte[] encrypt = cipher.doFinal(byteContent);
            // 防止乱码，转换进制
            return parseByte2HexStr(encrypt);
        } catch (Exception e) {
            log.error(Atom.ERROR_MSG, e);
        }
        return null;
    }

    private static SecretKeySpec createCipher(String password) throws NoSuchAlgorithmException {
        // 创建AES的Key生产者
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes(StandardCharsets.UTF_8));
        // 利用用户密码作为随机数初始化出(密码一样，就可以解密)
        kgen.init(128, random);
        // 根据用户密码，生成一个密钥
        SecretKey secretKey = kgen.generateKey();
        // 返回基本编码格式的密钥，如果此密钥不支持编码，则返回null
        byte[] enCodeFormat = secretKey.getEncoded();
        // 转换为AES专用密钥
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        return key;
    }

    /**
     * @auther: Ragty
     * @describe: AES解密器
     * @param: [content, password]
     * @return: byte[]
     * @date: 2019/1/18
     */
    public static String decrypt(String content, String password) {
        try {
            SecretKeySpec key = createCipher(password);
            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES");
            // 初始化为解密模式的密码器
            cipher.init(Cipher.DECRYPT_MODE, key);
            // 解密
            byte[] results = cipher.doFinal(parseHexStr2Byte(content));
            return new String(results);
        } catch (Exception e) {
            log.error(Atom.ERROR_MSG, e);
        }
        return null;
    }

    /**
     * 将二进制转换为十六进制
     *
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(byte[] buf) {
        StringBuilder sbd = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sbd.append(hex.toUpperCase());
        }
        return sbd.toString();
    }

    /**
     * @auther: Ragty
     * @describe: 十六进制转换二进制
     * @param: [hexStr]
     * @return: byte[]
     * @date: 2019/1/18
     */
    private static byte[] parseHexStr2Byte(String hexStr) {
        byte[] result = new byte[0];
        if (hexStr.length() < 1) {
            return result;
        }
        result = new byte[hexStr.length() / Atom.CONSTANT_TWO];
        for (int i = 0; i < hexStr.length() / Atom.CONSTANT_TWO; i++) {
            int high =
                    Integer.parseInt(hexStr.substring(i * Atom.CONSTANT_TWO, i * Atom.CONSTANT_TWO + 1), 16);
            int low =
                    Integer.parseInt(
                            hexStr.substring(
                                    i * Atom.CONSTANT_TWO + 1, i * Atom.CONSTANT_TWO + Atom.CONSTANT_TWO),
                            16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}
